<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="250px"
      v-loading="formLoading"
    >
      <el-form-item label="Name" prop="name">
        <el-input v-model="formData.name" placeholder="Please input the Name" />
      </el-form-item>
      <el-form-item label="Age" prop="age">
        <el-input v-model="formData.age" placeholder="Please input the Age" />
      </el-form-item>
      <el-form-item label="Data Source Name" prop="datasourceName">
        <el-input
          v-model="formData.datasourceName"
          placeholder="Please input the Data Source Name"
        />
      </el-form-item>

      <el-form-item label="Clinical Diagnosis Type" prop="clinicalDiagnosisType">
        <el-select v-model="formData.clinicalDiagnosisType" placeholder="Please select ">
          <el-option
            v-for="dict in getIntDictOptions('临床诊断')"
            :key="dict.value"
            :value="dict.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="Visibility of Germ Cells" prop="germCellsVisible">
        <el-radio-group v-model="formData.germCellsVisible">
          <el-radio
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :label="dict.value"
            :key="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="Chromosome Karyotype" prop="karyotype">
        <el-select v-model="formData.karyotype" placeholder="Please select ">
          <el-option
            v-for="dict in getIntDictOptions('染色体核型')"
            :key="dict.value"
            :value="dict.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="Presence of Genetic Pedigree" prop="isGeneticFamily">
        <el-radio-group v-model="formData.isGeneticFamily">
          <el-radio
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :label="dict.value"
            :key="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="Data Type" prop="dataType">
        <el-select v-model="formData.dataType" placeholder="Please select ">
          <el-option
            v-for="dict in getIntDictOptions('数据类型')"
            :key="dict.value"
            :value="dict.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="Remarks" prop="notes">
        <el-input type="textarea" v-model="formData.notes" placeholder="Please input the Remarks" />
      </el-form-item>
      <el-form-item
        v-if="!formData.isDataUploaded"
        label="Upload File(or manually enter path)"
        prop="inputOrUpload"
      >
        <el-switch v-model="formData.inputOrUpload" active-value="upload" inactive-value="input" />
      </el-form-item>
      <el-form-item
        v-if="formData.inputOrUpload === 'upload' && !formData.isDataUploaded"
        label="Upload Sample File"
        id="uploadFormItem"
      >
        <el-upload
          :disabled="formType.value === 'update' && formData.isDataUploaded === true"
          class="upload-demo"
          multiple
          v-model:file-list="fileList"
          :limit="3"
          :auto-upload="false"
        >
          <div style="width: 30px; height: 30px; color: black; margin-right: 4px">
            <svg
              xmlns="http://www.w3.org/2000/svg"
              xmlns:xlink="http://www.w3.org/1999/xlink"
              viewBox="0 0 24 24"
            >
              <path
                d="M7.4 10h1.59v5c0 .55.45 1 1 1h4c.55 0 1-.45 1-1v-5h1.59c.89 0 1.34-1.08.71-1.71L12.7 3.7a.996.996 0 0 0-1.41 0L6.7 8.29c-.63.63-.19 1.71.7 1.71zM5 19c0 .55.45 1 1 1h12c.55 0 1-.45 1-1s-.45-1-1-1H6c-.55 0-1 .45-1 1z"
                fill="currentColor"
              />
            </svg>
          </div>
          <span>Choose File</span>
        </el-upload>
        <!--                <el-button type="primary" @click="uploadFileMethod" style="margin-left: 10px">开始上传</el-button>-->
      </el-form-item>
      <el-form-item
        v-else-if="formData.inputOrUpload === 'input' && !formData.isDataUploaded"
        label="Input Sample File path/dir"
        id="uploadFormItem"
      >
        <el-input v-model="formData.dataPath"></el-input>
        <!--                <el-button type="primary" @click="uploadFileMethod" style="margin-left: 10px">开始上传</el-button>-->
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">Confirm</el-button>
      <el-button @click="dialogVisible = false">Cancel</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { DICT_TYPE, getBoolDictOptions, getIntDictOptions } from '@/utils/dict'
import * as DatasourceApi from '@/api/sca/datasource'
import { ElMessage, FormInstance, UploadUserFile } from 'element-plus'
import { uploadFile } from '@/api/sca/datasource'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改

const fileList = ref<UploadUserFile[]>([])

const formData = ref({
  id: undefined,
  datasourceName: undefined,
  name: undefined,
  age: undefined,
  clinicalDiagnosisType: undefined,
  germCellsVisible: undefined,
  karyotype: undefined,
  isGeneticFamily: undefined,
  dataType: undefined,
  dataPath: undefined,
  files: '',
  notes: undefined,
  isDataUploaded: undefined,
  inputOrUpload: 'upload'
})
const validateDataType = (rule: any, value: any, callback: any) => {
  if (fileList.value.length !== 0 && value === '') {
    callback(new Error('Please select data type'))
  } else {
    callback()
  }
}
const formRules = reactive({
  datasourceName: [{ required: true, message: 'Required', trigger: 'blur' }],
  name: [{ required: true, message: 'Required', trigger: 'blur' }],
  age: [{ required: true, message: 'Required', trigger: 'blur' }],
  clinicalDiagnosisType: [{ required: true, message: 'Required', trigger: 'change' }],
  germCellsVisible: [{ required: true, message: 'Required', trigger: 'change' }],
  karyotype: [{ required: true, message: 'Required', trigger: 'change' }],
  isGeneticFamily: [{ required: true, message: 'Required', trigger: 'change' }],
  dataType: [{ validator: validateDataType, trigger: 'change' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await DatasourceApi.getDatasource(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    if (formData.value.inputOrUpload === 'upload') {
      if (fileList.value.length > 0) {
        const fileFormData = new FormData()
        for (let i = 0; i < fileList.value.length; i++) {
          let file: any = fileList.value[i]
          console.log(file)
          fileFormData.append('files', file.raw)
        }

        const uploadRes = await uploadFile(fileFormData)
          .then((res: any) => {
            console.log(res)
            formData.value.files = JSON.stringify(res['data'])
          })
          .catch((err) => {
            console.log(err)
          })
        console.log(uploadRes)
      }
    }
    const data = formData.value as unknown as DatasourceApi.DatasourceVO
    if (formType.value === 'create') {
      await DatasourceApi.createDatasource(data)
      message.success(t('common.createSuccess'))
    } else {
      await DatasourceApi.updateDatasource(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    datasourceName: undefined,
    name: undefined,
    age: undefined,
    clinicalDiagnosisType: undefined,
    germCellsVisible: undefined,
    karyotype: undefined,
    isGeneticFamily: undefined,
    dataType: undefined,
    dataPath: undefined,
    files: '',
    isDataUploaded: undefined,
    inputOrUpload: 'upload',
    notes: undefined
  }
  formRef.value?.resetFields()
}
</script>
